package io.alexkozlov.jpointfedagent.operator;

import io.alexkozlov.jpointfedagent.DiscoveryController;
import io.alexkozlov.jpointfedagent.model.crd.ServiceExport;
import io.alexkozlov.jpointfedagent.model.crd.ServiceImport;
import io.fabric8.kubernetes.client.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

@Component
public class K8SOperator {
    private static final Logger LOGGER = LoggerFactory.getLogger(K8SOperator.class);

    @Value("${cluster.name}")
    private String clusterName;

    private final DiscoveryController discoveryController;

    public K8SOperator(DiscoveryController discoveryController) throws IOException {
        this.discoveryController = discoveryController;
        Init();
    }

    public void Init() throws IOException {
        KubernetesClient client = new DefaultKubernetesClient();
        if (System.getenv("DEBUG")!= null) {
            LOGGER.info("DEBUG MODE");
            String text = Files.readString(Paths.get(System.getenv("KUBECONFIG")));
            client = new DefaultKubernetesClient(Config.fromKubeconfig(text));
        }

        LOGGER.info("*** Start Service Import operator ***");
        client.resources(ServiceImport.class).watch(new ServiceImportWatcher(client, discoveryController));
        LOGGER.info("*** Start Service Export operator ***");
        client.resources(ServiceExport.class).watch(new ServiceExportWatcher(discoveryController, this.clusterName));
    }
}
